﻿/*
2013年10月30日 小徐
ct_link_cctalkOpen 自定义
*/
var ctcalluser = {
    baseUrl: '//service.cctalk.com',    /*基础url*/
    ctUrl: '',    /*呼出连接*/
    original:'ctim://sendmsg?&talkuserid=',
    init: function (config) {
        this.ctConfig = config; 
       // this.baseUrl=document.douc
        /*构建容器承载展示*/
        var styleObject = '<a href="javascript:" title=""  class="ct_link_cctalkOpen"></a>';
       
        $(this.ctConfig.element).each(function (index, element) {
            if (ctcalluser.ctConfig.source == "deskmate") {
                if ($.trim($(element).html()) == "") {
                    $(element).append(styleObject);
                }
            }
            else {
                $(element).append(styleObject);
            }
        });

        $(".ct_link_cctalkOpen:empty").each(function (index, element) {
            if (ctcalluser.ctConfig.source == "deskmate") {
                if ($.trim($(element).html()) == "") {
                    $(element).click(function () {
                        ctcalluser.showCtPanl(ctcalluser.ctConfig.userID[index], RegExp(" AppleWebKit/").test(navigator.userAgent));
                        this.blur();
                    });
                }
            }
            else {
                $(element).click(function () {
                    ctcalluser.showCtPanl(ctcalluser.ctConfig.userID[index], RegExp(" AppleWebKit/").test(navigator.userAgent));
                    this.blur();
                });
            }
           
        });
        /*非ie，已安装*/
        if (RegExp(" AppleWebKit/").test(navigator.userAgent) && $.cookie('ct') == 1) {
            $(".ct_link_cctalkOpen").each(function (index, element) {
                $(element).attr("href", ctcalluser.original + ctcalluser.ctConfig.userID[index]);
            });
        }
        else {  /*追加flash检测*/
            var flash = '<embed style="position:absolute;top:-100px;left:-100px" src="' + this.baseUrl + '/media/cctalk_out.swf?autocheck=1" quality="high" width="1" height="1" allowscriptaccess="always" type="application/x-shockwave-flash" /><div id="ct_showiframe"></div>';
            $("body").append(flash);
        }
        $("body").append('<link href="' + this.baseUrl + '/api/ctcalls/base.css" rel="stylesheet" />');
        this.checkIsOnLine();
    },
    checkIsOnLine: function () {      /*检查是否登录*/
        $(".ct_link_cctalkOpen:empty").each(function (index, element) {
            if (ctcalluser.ctConfig.source == "deskmate") {
                if ($.trim($(element).html()) == "") {
                    ctcalluser.ajaxGetData('/api/ctcalluser.asmx/CheckIsOnLine?userid=' + ctcalluser.ctConfig.userID[index], "", true, function (data) {
                        if (data.d) {
                            $(element).attr("title", "CCtalk聊天");
                            $(element).append('<img class="ct_link_iconimg"  src="' + ctcalluser.baseUrl + '/api/ctcalls/' + (ctcalluser.checkIsIE6() ? 'online_icon.gif' : 'online_icon.png') + '" />聊天');
                        }
                        else {
                            $(element).attr("title", "CCtalk留言");
                            $(element).append('<img class="ct_link_iconimg"  src="' + ctcalluser.baseUrl + '/api/ctcalls/' + (ctcalluser.checkIsIE6() ? 'unline_icon.gif' : 'unline_icon.png') + '"/>留言');
                        }

                    });
                };
            }
            else {
                ctcalluser.ajaxGetData('/api/ctcalluser.asmx/CheckIsOnLine?userid=' + ctcalluser.ctConfig.userID[index], "", true, function (data) {
                    if (data.d) {
                        $(element).attr("title", "CCtalk聊天");
                        $(element).append('<img class="ct_link_iconimg"  src="' + ctcalluser.baseUrl + '/api/ctcalls/' + (ctcalluser.checkIsIE6() ? 'online_icon.gif' : 'online_icon.png') + '" />聊天');
                    }
                    else {
                        $(element).attr("title", "CCtalk留言");
                        $(element).append('<img class="ct_link_iconimg"  src="' + ctcalluser.baseUrl + '/api/ctcalls/' + (ctcalluser.checkIsIE6() ? 'unline_icon.gif' : 'unline_icon.png') + '"/>留言');
                    }

                });
            }
        });
    },
    checkUserIsOnLine: function (userid,v) {      /*检查用户是否在线*/
        ctcalluser.ajaxGetData('/api/ctcalluser.asmx/CheckIsOnLine?userid=' + userid, "", true, v);
    },
    showCtPanl: function (id) {           /*显示操作面板*/
        ctcalluser.statistics();
        return false;
    },
    ajaxGetData: function (url, parameter, isAsync, invokeFun) {
        $.ajax({
            type: "get",
            dataType: "jsonp",
            async: isAsync,
            contentType: "application/json; charset=utf-8",
            url: this.baseUrl + url,
            data: parameter,
            success: invokeFun
        });
    },
    closeWindow: function () {              /*关闭操作面板*/
        $("#winmedal-box").hide();
        $("#ct_showiframe").hide();
        this.showCtPanl = function (id) {
            ctcalluser.ctUrl = ctcalluser.original + id
            $("#ct_showiframe").show();
            $("#winmedal-box").show();
        };
    },
    checkIsIE6: function () {
        return $.browser.msie && ($.browser.version == "6.0");
    },
    alreadyInstall: function () {   /*已经安装*/
        var  isnotice=$("#winmedal-box input").is(':checked');
        this.closeWindow();
        window.location.href = this.ctUrl;
        if (isnotice) {
            $.cookie('ct', '1', { expires: 30 });
            this.showCtPanl = function (id) {           /*显示操作面板*/
                return true;
            }
            $(".ct_link_cctalkOpen").each(function (index, element) {
                $(element).attr("href", ctcalluser.original + ctcalluser.ctConfig.userID[index]);
            });
        }
    },
    showClassPanl: function (type)
    {
        if (type) {

            var htmlc = '<div id="winmedal-content-border" style="padding-bottom:14px;"><span onclick="ctcalluser.closeWindow();" id="winmedal-close">Close</span><div id="pnl_setup" style="margin:5px 0px 0px 85px"><div style="float:left;margin:4px 0px 0px 0px;color:#7BBB29;font-size:24px;text-align: center;padding-left: 5px;"><img style="width:30px;height:30px;float:left;" src="http://service.cctalk.com/api/ctcalls/ct256.png" /><span style="font-size: 19px;margin-left: 20px;line-height: 29px;display: block;width: 179px;color:#0D98C9;font-family:微软雅黑;"> 确认安装CCTalk</span></div><div class="clear"></div></div><div style="height:47px;margin:10px 0px 0px 17px;color:#9D9D9D;padding:5px 10px;"><span style="font-size:14px;">聊天、留言需要安装CCtalk，请先确认是否已经安装过。有很多免费课程哦！</span></div><div style="margin:10px 0px 10px 0px"><a href="http://class.hujiang.com/zt/cctalk/?ctopen={0}" target="_blank" style="float:right;margin-right:70px;" class="btnc" >未安装</a><a href="javascript:" style="float:left;margin-left:70px" class="btnc" onclick="ctcalluser.alreadyInstall()">已安装</a><div class="clear"></div></div><div style="margin:10px 13px 0px 10px"><input type="checkbox" id="chk_showAgain" style="_float:left;"><label for="chk_showAgain" style="_float:left;margin-left:5px" class="gray">不再显示此提示</label></div></div>'
            $("#winmedal-box").html(htmlc.replace("{0}",ctcalluser.ctConfig.source));

        }
        else {
            var htmlc = '<div id="winmedal-content-border"><span onclick="ctcalluser.closeWindow();" id="winmedal-close">Close</span><div style="height:47px;margin:20px 0px 0px 7px;color:#9D9D9D;padding:5px 10px;font-size:14px;margin-top:30px;">安装<span style="color:#008000;">CCtalk</span>,就可以和沪友及时聊天啦，还可以享有免费的语音公开课哦，快去下载吧。</div><div style="margin:25px 0px 40px 0px"><a href="javascript:"  style="float:right;margin-right:70px;line-height:40px;" class="btnc" onclick="ctcalluser.closeWindow();">以后下载</a><a  href="http://class.hujiang.com/zt/cctalk/?ctopen={0}" target="_blank" style="float:left;margin-left:70px;line-height:40px;" class="btnc" >马上下载</a><div class="clear"></div></div><div style="margin:10px 13px 0px 10px"></div></div>';
            $("#winmedal-box").html(htmlc.replace("{0}", ctcalluser.ctConfig.source));
        }
        $("#winmedal-box").show();
        $("#ct_showiframe").show();
    },
    ctFlashInvoke: function (status) {        /*cctalk是否安装回调方法*/
        if (status == 1) {
            $(".ct_link_cctalkOpen").each(function (index, element) {
                $(this).attr("href", ctcalluser.original + ctcalluser.ctConfig.userID[index]);
            });
        }
        else {
            ctcalluser.showCtPanl = function (id, opentype) {
                var iframehtml = '<div style="display:none;" id="winmedal-box" class="winmedal_success"></div>';
                $("#ct_showiframe").html(iframehtml);
                ctcalluser.ctUrl = ctcalluser.original + id
                ctcalluser.showClassPanl(opentype);
                ctcalluser.statistics();
                return true;
            };
        }
    },
    statistics: function () { /*统计*/

        var yesdata = "&refe=" + escape(document.referrer) + "&random=" + Math.random();
        var el = document.createElement("img");
        el.style.display = "none";
        el.style.width = "0px";
        el.style.height = "0px";
        el.src = "http://webclick.hujiang.com/clickgather.ashx?counter=bulo_ct_link" + yesdata;
        document.body.appendChild(el);

    }
};
ctcalluser.ctConfig = {
    userID: [],     /*用户ID*/
    IP: '',         /*用户ip*/
    appearType: 0,  /*展现类型*/
    element: null,    /*容器元素*/
    source:'unknow'     /*来源*/
};

//cctalk是否安装回调方法
function getCCTalkStatus(status) {
   // $("body").append(status);
    ctcalluser.ctFlashInvoke(status);
}


(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else {
        // Browser globals.
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch (e) { }
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write
        if (value !== undefined && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {};

        
        var cookies = document.cookie ? document.cookie.split('; ') : [];

        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = parts.join('=');

            if (key && key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) === undefined) {
            return false;
        }

        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));